import React from 'react';
import _ from 'underscore';
import View from 'lib/View.jsx';
import Layout from '../common/layout.jsx';
import GridWidget from 'lib/components/GridWidget.jsx';
import Card from 'lib/components/card.jsx';
import MainViewScope from './MainViewScope.es6';
import dispatcher from 'lib/dispatcher';
import ElementModal from './ElementModal.jsx';
import { Confirm } from 'lib/components/Confirm.jsx';
import { Success, Warning } from 'lib/components/Notify.jsx';
import DefaultNoDataElement from 'lib/util/defaultNoDataElement.jsx';

class MainView extends View {
  constructor(props) {
    super(props);
    this.displayName = 'MainView';
  }

  handleRemoveElement({id}) {
    Confirm('确认要删除这个关键元素？').then(() => {
      dispatcher.dispatch({
        $type: 'remove',
        id,
        callback: (status) => {
          if (status) {
            Success('删除成功');
          } else {
            Warning('删除失败，请重试');
          }
        }
      });
    });
  }

  handleMountElementModal(element = {}) {
    ElementModal.mount(element);
  }

  render() {
    let store = {
      loading: this.state.loading,
      data: this.state.elements
    },

    ELEMENTS_COLUMN = [
      {
        title: '名称',
        key: 'name',
        sortable: true,
        render: (fmtVal, element) => {
          return <a href={`element-analyse#/detail/${element.id}`}>{ fmtVal }</a>
        }
      },
      {
        title: 'URL',
        key: 'conditions',
        sortable: true,
        render: (fmtVal, element) => {
          return <span>{ element.conditions['http.url'].value }</span>;
        }
      },
      {
        title: '优先级',
        key: 'priority',
        sortable: true,
        width: '20%',
        render: (fmtVal, element) => {
          return <span>{ element.priority }</span>;
        }
      },
      {
        title: '操作',
        width: '10%',
        key: Math.random(),
        render: (_, element) => {
          return [
            <a key={ element.id + '1' } href="javascript:;" className="iconfont" onClick={ this.handleMountElementModal.bind(this, element) }>&#xe637;</a>,
            <a key={ element.id + '2' } href="javascript:;" className="iconfont" onClick={ this.handleRemoveElement.bind(this, element) }>&#xe61f;</a>
          ];
        }
      }
    ],

    nodataElement = <DefaultNoDataElement content={<span>尚未添加关键请求，<a href="javascript:;" onClick={ this.handleMountElementModal.bind(this) }>点我添加</a></span>} />;

    return (
      <Layout title="关键元素设置" subtitle="设置最关注的关键元素" hideVersion={true} hideTime={true}>
        <div className="elements-grid box">
          <Card title="网络请求" extra={<a href="javascript:;" className="btn-green" onClick={ this.handleMountElementModal.bind(this) }>添加关键请求</a>}>
            <GridWidget nodataElement={nodataElement} store={store} cols={ ELEMENTS_COLUMN } />
          </Card>
        </div>
      </Layout>
    );
  }
}

MainView.defaultProps = {
  Scope: MainViewScope
};

export default MainView;
